package com.aaa.vegetablemarketexpress.controller;

import com.aaa.vegetablemarketexpress.entity.Order;
import com.aaa.vegetablemarketexpress.entity.User;
import com.aaa.vegetablemarketexpress.service.OrderService;
import com.aaa.vegetablemarketexpress.util.Result;
import com.aaa.vegetablemarketexpress.util.ResultUtil;
import lombok.extern.log4j.Log4j2;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @FileName: OrderController
 * @Description: 订单控制器
 * @Author:
 * @CreateTime: 2025/9/15
 * @Version: 1.0.0
 */
@RestController
@RequestMapping("/order")
@Log4j2
public class OrderController {

    @Resource
    private OrderService orderService;

    /**
     * 创建订单
     * @param order 订单信息
     * @return
     */
    @PostMapping("/createOrder")
    public Result createOrder(@RequestBody Order order, HttpSession session) {
        try {
            orderService.createOrder(order, session);
            return ResultUtil.success("订单创建成功");
        } catch (Exception e) {
            log.error("创建订单失败", e);
            return ResultUtil.failed("订单创建失败: " + e.getMessage());
        }
    }

    /**
     * 获取支付状态
     * @param orderNo 订单编号
     * @return
     */
    @GetMapping("getPayStatus/{orderNo}")
    public Result getPayStatus(@PathVariable("orderNo") String orderNo) {
        Map<String, String> map = orderService.getPayStatus(orderNo);
        return ResultUtil.success(map);
    }

    /**
     * 生成支付二维码
     * @param order
     * @return
     */
    @PostMapping("getNativeCodeUrl")
    public Result getNativeCodeUrl(@RequestBody Order order){
        Map map = orderService.getNativeByOrder(order);
        return ResultUtil.success(map);
    }

    /**
     * 更新订单状态
     * @param order 订单信息
     * @return
     */
    @PostMapping("/updateStatus")
    public Result updateStatus(@RequestBody Order order) {
        try {
            orderService.updateOrderStatus(order);
            return ResultUtil.success("订单状态更新成功");
        } catch (Exception e) {
            log.error("更新订单状态失败", e);
            return ResultUtil.failed("订单状态更新失败: " + e.getMessage());
        }
    }
    /**
     * 获取商家订单列表
     * @param session 用户会话
     * @return 订单列表
     */
    @GetMapping("/getShopOrders")
    public Result getShopOrders(HttpSession session) {
        try {
            Map<String, Object> request = new HashMap<>();
            return ResultUtil.success(orderService.getShopOrders(request, session));
        } catch (Exception e) {
            log.error("获取商家订单列表失败", e);
            return ResultUtil.failed("获取订单列表失败: " + e.getMessage());
        }
    }

    /**
     * 发货单个商品
     * @param itemId 商品明细ID
     * @param session 用户会话
     * @return 是否成功
     */
    @PostMapping("/shipItem/{itemId}")
    public Result shipItem(@PathVariable Long itemId, HttpSession session) {
        try {
            boolean result = orderService.shipItem(itemId, session);
            if (result) {
                return ResultUtil.success("发货成功");
            } else {
                return ResultUtil.failed("发货失败");
            }
        } catch (Exception e) {
            log.error("发货失败", e);
            return ResultUtil.failed("发货失败: " + e.getMessage());
        }
    }


    /**
     * 获取用户订单列表（包含订单项和操作记录）
     * @param session 用户会话
     * @return 订单列表
     */
    @GetMapping("/getUserOrders")
    public Result getUserOrders(HttpSession session) {
        try {
            User currentUser = (User) session.getAttribute("userInfo");
            if (currentUser == null) {
                return ResultUtil.failed("用户未登录");
            }

            Map<String, Object> request = new HashMap<>();
            return ResultUtil.success(orderService.getUserOrders(request, session));
        } catch (Exception e) {
            log.error("获取用户订单列表失败", e);
            return ResultUtil.failed("获取订单列表失败: " + e.getMessage());
        }
    }

    /**
     * 用户确认收货
     * @param request 请求参数（包含订单ID和订单编号）
     * @param session 用户会话
     * @return 操作结果
     */
    @PostMapping("/confirmReceipt")
    public Result confirmReceipt(@RequestBody Map<String, Object> request, HttpSession session) {
        try {
            Long orderId = Long.valueOf(request.get("orderId").toString());
            String orderNo = request.get("orderNo").toString(); // 获取订单编号
            boolean result = orderService.confirmReceipt(orderId, orderNo, session);
            if (result) {
                return ResultUtil.success("确认收货成功");
            } else {
                return ResultUtil.failed("确认收货失败");
            }
        } catch (Exception e) {
            log.error("确认收货失败", e);
            return ResultUtil.failed("确认收货失败: " + e.getMessage());
        }
    }




    /**
     * 获取订单趋势数据
     */
    @GetMapping("/statistics/trend")
    public Result getOrderTrendData(@RequestParam("startDate") String startDateStr,
                                    @RequestParam("endDate") String endDateStr) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date startDate = sdf.parse(startDateStr);
            Date endDate = sdf.parse(endDateStr);

            List<Map<String, Object>> data = orderService.getOrderTrendData(startDate, endDate);
            return ResultUtil.success(data);
        } catch (Exception e) {
            log.error("获取订单趋势数据失败", e);
            return ResultUtil.failed("获取订单趋势数据失败: " + e.getMessage());
        }
    }

    /**
     * 获取订单状态统计
     */
    @GetMapping("/statistics/status")
    public Result getOrderStatusStats() {
        try {
            List<Map<String, Object>> data = orderService.getOrderStatusStats();
            return ResultUtil.success(data);
        } catch (Exception e) {
            log.error("获取订单状态统计失败", e);
            return ResultUtil.failed("获取订单状态统计失败: " + e.getMessage());
        }
    }

    /**
     * 获取商品销售排行
     */
    @GetMapping("/statistics/product-ranking")
    public Result getProductSalesRanking(@RequestParam(defaultValue = "10") int limit) {
        try {
            List<Map<String, Object>> data = orderService.getProductSalesRanking(limit);
            return ResultUtil.success(data);
        } catch (Exception e) {
            log.error("获取商品销售排行失败", e);
            return ResultUtil.failed("获取商品销售排行失败: " + e.getMessage());
        }
    }

    /**
     * 根据订单编号生成支付二维码
     * @param orderNo 订单编号
     * @return 支付二维码信息
     */
    @PostMapping("/getNativeCodeUrlByOrderNo")
    public Result getNativeCodeUrlByOrderNo(@RequestParam("orderNo") String orderNo) {
        try {
            Map map = orderService.getNativeByOrderNo(orderNo);
            if (map != null) {
                return ResultUtil.success(map);
            } else {
                return ResultUtil.failed("生成支付二维码失败");
            }
        } catch (Exception e) {
            log.error("生成支付二维码失败", e);
            return ResultUtil.failed("生成支付二维码失败: " + e.getMessage());
        }
    }


}
